package org.yate.oa.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.yate.oa.model.HistoryEntity;
import org.yate.oa.model.LoginEntity;
import org.yate.oa.service.IHistoryService;
import org.yate.oa.service.imp.HistoryService;
import org.yate.oa.service.imp.OrgService;
import org.yate.oa.utils.ExportExcel;
import org.yate.oa.utils.Pagination;

import com.alibaba.fastjson.JSONObject;

/**
 * 任务历史记录管理
 * 
 * @author ZYY
 * 
 */
@WebServlet(urlPatterns = { "/history/get", "/history/post", "/history/put", "/history/delete" }, asyncSupported = false)
public class HistoryController extends BaseServletController {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
		doPost(req, rsp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
		String type = req.getParameter("type");
		PrintWriter out = rsp.getWriter();
		JSONObject json = new JSONObject();
		if (StringUtils.isEmpty(type)) {
			json.put("code", "401");
			json.put("msg", "type cannot be null");
			out.println(json);
			out.flush();
			out.close();
			return;
		}
		if (type.equals("get")) {
			getHistory(req, rsp);
		} else if (type.equals("getById")) {
			getHistoryByApproerId(req, rsp);
		} else if (type.equals("all")) {
			getAll(req, rsp);
		} else if (type.equals("excel")) {
			export2Excel(req, rsp);
		} else if (type.equals("getByCreater")) {
			getHistoryByCreater(req, rsp);
		}
	}

	private void getHistory(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
		PrintWriter out = rsp.getWriter();
		JSONObject json = new JSONObject();
		LoginEntity le = (LoginEntity) req.getSession().getAttribute("user");
		if (le == null) {
			json.put("code", "401");
			json.put("msg", "current user is null");
			out.println(json);
			out.flush();
			out.close();
			return;
		}
		String taskType = req.getParameter("taskType");
		IHistoryService historyService = this.springCtx.getBean(HistoryService.class);
		String page = req.getParameter("page");
		int pageIndex = 0;
		if (!StringUtils.isEmpty(page)) {
			pageIndex = Integer.parseInt(page);
		}
		String[] strs = { le.getUserId() + "", taskType };
		Pagination<HistoryEntity> data = historyService.getEntitiesByCreaterId(pageIndex, 10, "", "", strs);
		json.put("status", "200");
		json.put("data", data);
		out.println(json);
		out.flush();
		out.close();
	}

	private void getHistoryByCreater(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
		PrintWriter out = rsp.getWriter();
		JSONObject json = new JSONObject();
		String createrId = req.getParameter("createrId");
		IHistoryService historyService = this.springCtx.getBean(HistoryService.class);
		String page = req.getParameter("page");
		int pageIndex = 0;
		if (!StringUtils.isEmpty(page)) {
			pageIndex = Integer.parseInt(page);
		}
		String[] strs = { createrId };
		Pagination<HistoryEntity> data = historyService.getEntitiesByCreaterId2(pageIndex, 10, "", "", strs);
		json.put("status", "200");
		json.put("data", data);
		out.println(json);
		out.flush();
		out.close();
	}

	private void getHistoryByApproerId(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
		PrintWriter out = rsp.getWriter();
		JSONObject json = new JSONObject();
		LoginEntity le = (LoginEntity) req.getSession().getAttribute("user");
		if (le == null) {
			json.put("code", "401");
			json.put("msg", "current user is null");
			out.println(json);
			out.flush();
			out.close();
			return;
		}
		IHistoryService historyService = this.springCtx.getBean(HistoryService.class);
		String page = req.getParameter("page");
		int pageIndex = 0;
		if (!StringUtils.isEmpty(page)) {
			pageIndex = Integer.parseInt(page);
		}
		String[] strs = { le.getUserId() + "" };
		Pagination<HistoryEntity> data = historyService.getEntitiesByApproverId(pageIndex, 10, "", "", strs);
		json.put("status", "200");
		json.put("data", data);
		out.println(json);
		out.flush();
		out.close();
	}

	private void getAll(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
		PrintWriter out = rsp.getWriter();
		JSONObject json = new JSONObject();
		String dataType = req.getParameter("dataType");
		String dataStatus = req.getParameter("dataStatus");
		String searchVal = req.getParameter("searchVal");
		String searchVal2 = req.getParameter("searchVal2");
		String orgId = req.getParameter("branch");
		IHistoryService historyService = this.springCtx.getBean(HistoryService.class);
		String page = req.getParameter("page");
		int pageIndex = 0;
		if (!StringUtils.isEmpty(page)) {
			pageIndex = Integer.parseInt(page);
		}
		if (!searchVal.equals("") && !searchVal2.equals("")) {
			searchVal += " 23:59:59";
			searchVal2 += " 23:59:59";
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("dataType", dataType);
		map.put("dataStatus", dataStatus);
		map.put("searchVal", searchVal);
		map.put("searchVal2", searchVal2);
		List<Integer> ids = new ArrayList<Integer>();
		if (!orgId.equals("")) {
			OrgService orgService = this.springCtx.getBean(OrgService.class);
			ids.add(Integer.parseInt(orgId));
			PerformanceController.queryOrd(ids, Integer.parseInt(orgId), orgService);
		}
		map.put("ids", ids.size() == 0 ? null : ids);
		Pagination<HistoryEntity> data = historyService.getEntitieSearch(pageIndex, 10, "", "", map);
		json.put("status", "200");
		json.put("data", data);
		out.println(json);
		out.flush();
		out.close();
	}

	private void export2Excel(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
		rsp.reset();
		String fileName = "审批数据" + sdf.format(new Date());
		if (req.getHeader("user-agent").indexOf("MSIE") != -1) {
			fileName = java.net.URLEncoder.encode(fileName, "utf-8") + ".xls";
		} else {
			fileName = new String(fileName.getBytes("utf-8"), "iso-8859-1") + ".xls";
		}
		rsp.setHeader("Content-disposition", "attachment;filename=" + fileName);
		rsp.setContentType("application/msexcel;charset=UTF-8");
		ExportExcel<HistoryEntity> ex = new ExportExcel<HistoryEntity>();
		String dataType = req.getParameter("dataType") == null ? "" : req.getParameter("dataType");
		String dataStatus = req.getParameter("dataStatus") == null ? "" : req.getParameter("dataStatus");
		String searchVal = req.getParameter("searchVal") == null ? "" : req.getParameter("searchVal");
		String searchVal2 = req.getParameter("searchVal2") == null ? "" : req.getParameter("searchVal2");
		if (!searchVal.equals("") && !searchVal2.equals("")) {
			searchVal += " 23:59:59";
			searchVal2 += " 23:59:59";
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("dataType", dataType);
		map.put("dataStatus", dataStatus);
		map.put("searchVal", searchVal);
		map.put("searchVal2", searchVal2);
		String branch = req.getParameter("branch");
		if (!StringUtils.isEmpty(branch)) {
			List<Integer> ids = new ArrayList<Integer>();
			OrgService orgService = this.springCtx.getBean(OrgService.class);
			ids.add(Integer.parseInt(branch));
			PerformanceController.queryOrd(ids, Integer.parseInt(branch), orgService);
			map.put("ids", ids.size() == 0 ? null : ids);
		}
		IHistoryService hs = this.springCtx.getBean(HistoryService.class);
		List<HistoryEntity> list = hs.getEntitiesBySearch(map);
		OutputStream out = rsp.getOutputStream();
		String[] headers = { "发起者", "类型", "填报日期", "开始时间", "天数", "结束时间", "状态", "备注", "审批人", "审批结果", "请假类型" };
		ex.exportExcel("审批数据" + sdf.format(new Date()) + ".xls", headers, list, out);
		out.close();
	}
}
